﻿module Lhz.Page {
    export class Index extends Page {
        private cj = new Json.CycleJson();
        private sc = new StaticData();

        constructor() {
            super({ checkRole: false });
            if (this.indexInitialized) {
                this.$body = $("body");
                this.$mgTemplate = $("#mgTemplate");
                this.$maHeaderTemplate = $("#maHeaderTemplate");
                this.$mcContentTemplate = $("#mcContentTemplate");
                this.$dialogTemplate = $("#dialogTemplate")
                this.buildLayout();
                this.buildMenu();
                this.buildMainArea();
                this.buildLoading();
                this.bindSelect("#selectSkin", this.sc.getSkins());
                var skin = this.getLocalStorage("skin");
                if (skin) {
                    $("#selectSkin").val(skin);
                }
                $("#selectSkin").change(this, function (event) {
                    var index: Index = event.data;
                    var skin = $(event.target).val();
                    index.setLocalStorage("skin", skin);
                });
            }
        }

        private $body: any;

        private buildLayout() {
            this.$body.layout({
                defaults: {
                    closable: false,
                    resizable: false,
                    spacing_open: 0,
                    resizerDragOpacity: 0.5,
                    paneClass: "ui-widget-content",
                    resizerClass: "ui-widget-content",
                    togglerClass: "ui-widget-header",
                    togglerTip_open: "关闭",
                    togglerTip_closed: "打开"
                },
                west: {
                    closable: true,
                    resizable: true,
                    spacing_open: 8,
                    spacing_closed: 10
                }
            });
        }

        private $mgTemplate: any;
        private $maHeaderTemplate: any;
        private $mcContentTemplate: any;

        private buildMenu() {
            var mgs: Lhz.Interface.Menu.MenuGroup[] = [];
            for (var mg of this.sc.getMenuGroups()) {
                if (!this.user.IsAdmin) {
                    for (var i = mg.menuItems.length - 1; i >= 0; i--) {
                        if (mg.menuItems[i].admin) {
                            mg.menuItems.splice(i, 1);
                        }
                    }
                }
                if (mg.menuItems.length > 0) {
                    mgs.push(mg);
                }
            }

            this.$mgTemplate.tmpl(mgs).appendTo("#divMenu");
            $("#divMenu").accordion({ heightStyle: "content" });
            var $menuItems = $("#divMenu .index-menu-item");
            $menuItems.click(this, function (event) {
                var index: Index = event.data;
                var $menuItem = $(event.target);
                var menuItemEntity: Lhz.Interface.Menu.MenuItemEntity = {
                    id: $menuItem.attr("id"),
                    name: $menuItem.text(),
                    path: $menuItem.attr("menu-item-path"),
                    url: $menuItem.attr("page-url")
                };
                var headerId = "liMaHeader" + menuItemEntity.path;
                if ($("#" + headerId).length == 0) {
                    var $header: JQuery = index.$maHeaderTemplate.tmpl(menuItemEntity);
                    var $content: JQuery = index.$mcContentTemplate.tmpl(menuItemEntity);
                    $header.find(".ui-icon-close").click({ index: index, menuItemEntity: menuItemEntity }, function (event) {
                        var data: { index: Index, menuItemEntity: Lhz.Interface.Menu.MenuItemEntity } = event.data;
                        var index = data.index;
                        var menuItemEntity = data.menuItemEntity;
                        var iframe = frames["iframeMaContent" + menuItemEntity.path];
                        index.destroyIframe(iframe);
                        $header.remove();
                        $content.remove();
                        index.$maTab.tabs("refresh");
                        if (index.$maTab.tabs("option", "active") === false) {
                            index.setActivate();
                        }
                    })
                    $header.find(".ui-icon-refresh").click({ index: index, menuItemEntity: menuItemEntity }, function (event) {
                        var data: { index: Index, menuItemEntity: Lhz.Interface.Menu.MenuItemEntity } = event.data;
                        var index = data.index;
                        var menuItemEntity = data.menuItemEntity;
                        index.refreshIframe(frames["iframeMaContent" + menuItemEntity.path]);
                    })
                    $header.appendTo("#maHeader");
                    $content.appendTo("#divMainArea");
                }
                index.$maTab.tabs("refresh");
                index.setActivate(menuItemEntity.id, headerId);
            });
            $menuItems.mouseenter(function (event) {
                $(event.target).addClass("ui-state-hover");
            });
            $menuItems.mouseleave(function (event) {
                $(event.target).removeClass("ui-state-hover");
            });
        }

        private setActivate(menuItemId: string = null, headerId: string = null) {
            $("#divMenu .index-menu-item").removeClass("ui-state-active");
            if (menuItemId) {
                $("#" + menuItemId).addClass("ui-state-active");
            }

            if (headerId) {
                var $header = $("#" + headerId);
                var lis = $("#maHeader").find("li");
                for (var i = 0; i < lis.length; i++) {
                    var $item = $(lis[i]);
                    if ($item.attr("id") == $header.attr("id")) {
                        this.$maTab.tabs({ active: i });
                    }
                }
                $("#maHeader").find("li").find("span.ui-icon-refresh").hide();
                $header.find("span.ui-icon-refresh").show();
            }
        }

        private $maTab: JQuery;

        private buildMainArea() {
            var index: Index = this;
            this.$maTab = $("#divMainArea").tabs({
                heightStyle: "fill",
                activate: function (event, ui) {
                    var $header = ui.newTab;
                    var menuItemId = $header.attr("menuItemId");
                    var headerId = $header.attr("id");
                    index.setActivate(menuItemId, headerId);
                }
            });
            this.$maTab.find(".ui-tabs-nav").sortable({
                axis: "x",
                delay: 150,
                stop: function () {
                    index.$maTab.tabs("refresh");
                }
            });
        }

        private $dialogTemplate: any;
        private dialogIndex = 0;
        private dialogIdStart = "dialog-";
        private dialogDivStart = "dialog-div-";
        private dialogIframeStart = "dialog-iframe-";
        private dialogOptions: Lhz.Interface.Dialog.IndexDialogOptions[] = [];

        indexShowDialog(options: Lhz.Interface.Dialog.DialogOptions) {
            var dialogEntity: Lhz.Interface.Dialog.IndexDialogOptions = $.extend({
                index: this.dialogIndex,
                dialogId: this.dialogIdStart + this.dialogIndex,
                divId: this.dialogDivStart + this.dialogIndex,
                iframeName: this.dialogIframeStart + this.dialogIndex
            }, options);
            dialogEntity.indexDialogClosed = function (index, dialogEntity, returnValue) {
                if (dialogEntity.dialogClosed) {
                    dialogEntity.dialogClosed(returnValue, dialogEntity.data);
                }
                index.destroyIframe(frames[dialogEntity.iframeName]);
            };
            if (dialogEntity.url.indexOf("?") == -1) {
                dialogEntity.url += "?";
            } else {
                dialogEntity.url += "&";
            }
            dialogEntity.url += "dialogIndex=" + this.dialogIndex;
            this.$dialogTemplate.tmpl(dialogEntity).appendTo("body");
            $("#" + dialogEntity.divId).dialog({
                width: dialogEntity.width,
                height: dialogEntity.height,
                modal: true,
                resizable: false
            });
            this.dialogOptions.push(dialogEntity);
            this.dialogIndex++;
        }

        private getDialogEntitySelection(dialogIndexString: string): { index: number, item: Lhz.Interface.Dialog.IndexDialogOptions } {
            for (var i = this.dialogOptions.length - 1; i >= 0; i--) {
                var dialogEntity = this.dialogOptions[i];
                if (dialogEntity.index.toString() == dialogIndexString) {
                    return { index: i, item: dialogEntity };
                }
            }
        }

        indexGetDialogArguments(dialogIndexString: string): any {
            return this.getDialogEntitySelection(dialogIndexString).item.arguments;
        }

        indexCloseDialog(dialogIndexString: string, returnValue: any, serialize: boolean = false) {
            var dialogEntitySelection = this.getDialogEntitySelection(dialogIndexString);
            var dialogEntity = dialogEntitySelection.item;
            var $dialogDiv = $("#" + dialogEntity.divId);
            $dialogDiv.dialog("close");
            if (dialogEntity.indexDialogClosed) {
                if (serialize) {
                    returnValue = JSON.parse(returnValue);
                    this.cj.retrocycle(returnValue);
                }
                dialogEntity.indexDialogClosed(this, dialogEntity, returnValue);
            }
            this.dialogOptions.splice(dialogEntitySelection.index, 1);
        }

        private buildLoading() {
            $("#progressbar").progressbar({ value: false });
            $("#divLoading").dialog({ title: "操作中。。。", modal: true, autoOpen: false, height: 80 });
        }

        showLoading() {
            $("#divLoading").dialog("open"); new Object();
        }

        closeLoading() {
            $("#divLoading").dialog("close");
        }
    }
    $(function () {
        window["index"] = new Index();
    });
}
